/**国家汉字学生报名 */
<template>
  <div>
    <div v-if="indexSee === 1">
      <condition-card @reset="reset" @search="onSubmit" label-position="right" label-width="150px">
        <el-row :gutter="24" style="height: 50px;">
          <!-- 学年学期 -->
          <el-col :span="8">
            <el-form-item :label="$t('subjectCompetitionBase.semester')">
              <calendar-select ref="semester" v-model="queryForm.condition.calendarId" :placeholder="$t('common.pla.pleaseSelect')" @load-done="calendarIdLoadDone"></calendar-select>
            </el-form-item>
          </el-col>
        </el-row>
      </condition-card>
      <el-card shadow="never" v-loading="loading" body-style="padding: 24px;" class="card-margin">
        <h1 class="condition-title">{{$t('studentsRegist.testList')}}</h1>
        <edu-table :pagination="false" :tooltipEffect="tooltipEffect" stripe :data="dataList" size="mini">
          <edu-table-column :label="$t('studentsRegist.testTitle')" prop="title"></edu-table-column>
          <edu-table-column :label="$t('computerGrade.examType')" prop="competitionType">
            <template slot-scope="scope">
              国家汉字应用水平
            </template>
          </edu-table-column>
          <edu-table-column :label="$t('subjectCompetitionBase.semester')" prop="calendarYearTerm" min-width="150"></edu-table-column>
          <edu-table-column :label="$t('studentsRegist.testTime')" prop="signUpEnd" min-width="250">
            <template slot-scope="scope">
              {{ scope.row.signUpStart+'/'+scope.row.signUpEnd}}
            </template>
          </edu-table-column>
          <edu-table-column :label="$t('studentsRegist.status')" prop="statusName">
          </edu-table-column>
          <edu-table-column :label="$t('studentsRegist.operate')" fit min-width="200">
            <template slot-scope="props">
              <el-button v-if="props.row.status==0" :disabled="props.row.forbidden" type="text" @click="myRaiders(props.row)">{{$t('studentsRegist.myRaiders')}}</el-button>
              <el-button v-if="props.row.status!=0" :disabled="props.row.forbidden||props.row.status==1||props.row.status==2||props.row.status==3" type="text" @click="cancelRegistr(props.row)">{{$t('studentsRegist.cancelRegistr')}}</el-button>
              <el-button v-if="props.row.status!=0&&props.row.status!=1" :disabled="props.row.forbidden||props.row.status==2||props.row.status==3" type="text" @click="handleClick(props.row)">缴费</el-button>
              <el-button v-if="props.row.status==1&&props.row.cardId||props.row.status==2&&props.row.cardId" type="text" @click.stop="SeeClick(props.row)">查看准考证</el-button>
            </template>
          </edu-table-column>
          <!-- WHEN su.STATUS_ = 0 THEN '待报名'
              WHEN su.STATUS_ = 1 THEN '已报名'
              WHEN su.STATUS_ = 2 THEN '报名成功'
              WHEN su.STATUS_ = 3 THEN '无资格'
              WHEN su.STATUS_ = 4 THEN '未缴费 -->
        </edu-table>
        <el-row type="flex" class="row-bg" justify="end">
          <el-col>
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryForm.pageNum_" :page-sizes="[20, 40, 80, 100]" :page-size="queryForm.pageSize_" layout="total, sizes, prev, pager, next, jumper" :total="total_" style="float:right;margin-top:10px"></el-pagination>
          </el-col>
        </el-row>
      </el-card>
      <el-dialog :title="$t('studentsRegist.information')" :visible.sync="dialogVisible2" width="50%" :before-close="false">
        <div>
          <el-form :model="queryFormType" :inline="true" :rules="rules" ref="queryFormType">
            <el-row style="margin:20px">
              <el-col :span='12'>
                <span>{{$t('studentsRegist.examination')}}:</span>&nbsp;&nbsp;<span>国家汉字应用水平</span>
              </el-col>
              <el-col :span='12'>
                <span>{{$t('studentsRegist.college')}}:</span>&nbsp;&nbsp;<span>{{studentsRegist.collegeI18n}}</span>
              </el-col>
            </el-row>
            <el-row style="margin:20px">
              <el-col :span='12'>
                <span>{{$t('studentsRegist.studentNumber')}}:</span>&nbsp;&nbsp;<span>{{studentsRegist.studentId}}</span>
              </el-col>
              <el-col :span='12'>
                <span>{{$t('studentsRegist.subject')}}:</span>&nbsp;&nbsp;<span>{{studentsRegist.subject}}</span>
              </el-col>
            </el-row>
            <el-row style="margin:20px">
              <el-col :span='12'>
                <span>{{$t('studentsRegist.name')}}:</span>&nbsp;&nbsp;<span>{{studentsRegist.name}}</span>
              </el-col>
              <el-col :span='12'>
                <span>{{$t('studentsRegist.major')}}:</span>&nbsp;&nbsp;<span>{{studentsRegist.majorStr}}</span>
              </el-col>
            </el-row>
            <el-row style="margin:20px">
              <el-col :span='12'>
                <span>{{$t('studentsRegist.spellName')}}:</span>&nbsp;&nbsp;<span>{{studentsRegist.nameSpelling}}</span>
              </el-col>
              <el-col :span='12'>
                <span>{{$t('studentsRegist.enrollmentYear')}}:</span>&nbsp;&nbsp;<span>{{studentsRegist.entranceYear}}</span>
              </el-col>
            </el-row>
            <el-row style="margin:20px">
              <el-col :span='12'>
                <span>{{$t('studentsRegist.gender')}}:</span>&nbsp;&nbsp;<span>{{studentsRegist.sexI18n}}</span>
              </el-col>
              <el-col :span='12'>
                <span>{{$t('studentsRegist.examineeType')}}:</span>&nbsp;&nbsp;<span>{{studentsRegist.examStudentType}}</span>
              </el-col>
            </el-row>
            <el-row style="margin:20px">
              <el-col :span='12'>
                <el-form-item prop="cardType" :label="$t('studentsRegist.certificateType')">
                  <el-select @change="changeMajor" v-model="queryFormType.cardType" clearable style="width: 100%">
                    <el-option v-for="item in options.degreeType" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span='12'>
                <span v-if="this.studentsRegist.lockLimit == '1'">
                  {{$t('studentsRegist.signCampus')}}：{{studentsRegist.campusI18n}}
                </span>
                <el-form-item v-else :label="$t('studentsRegist.signCampus')">
                  <el-select disabled v-model="queryFormType.campus" clearable style="width: 100%">
                    <el-option v-for="item in examCampusLimitList" :key="item.value" :label="item.label" :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row style="margin:20px">
              <el-col :span='12'>
                <span>{{$t('studentsRegist.idNumber')}}:</span>&nbsp;&nbsp;<span>{{queryFormTypeList.idCardNo}}</span>
              </el-col>
            </el-row>
            <el-checkbox v-model="checked">{{$t('studentsRegist.subjects')}}</el-checkbox>
          </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="cancelFun">{{$t('studentsRegist.cancel')}}</el-button>
          <el-button type="primary" :disabled='!checked' @click="reliable2">{{$t('studentsRegist.determineRegistra')}}</el-button>
        </span>
      </el-dialog>
      <el-dialog :title="$t('studentsRegist.testExplana')" :visible.sync="dialogVisible" width="50%" :before-close="false">
        <!-- style="height:100px;overflow:auto;" -->
        <div class="testExplana" v-html="remark">
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">{{$t('studentsRegist.cancel')}}</el-button>
          <el-button type="primary" @click="reliable">确定</el-button>
        </span>
      </el-dialog>
      <el-dialog :title="$t('studentsRegist.reminder')" :visible.sync="dialogVisibleTime" width="50%" :before-close="false">
        <h2>
          {{$t('studentsRegist.registraTime')}}
        </h2>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisibleTime = false">{{$t('studentsRegist.confirm')}}</el-button>
          <!-- <el-button type="primary" @click="reliable">{{$t('studentsRegist.determineRegistra')}}</el-button> -->
        </span>
      </el-dialog>
    </div>
    <!-- 查看准考证 -->
    <div v-if="indexSee === 2" ref="msg" id="msg">
      <viewAdmissionCard :signUpId="signUpId" @change-exam-create-index="changeExamCreateIndex()"></viewAdmissionCard>
    </div>
  </div>
</template>
<script>
// import HistoryTable from 'common/src/views/studentsRegistStudent/component/HistoryTable';
import { mapState } from "vuex";
import { queryDic } from "common/src/api/dictionary";
import UTILS from "common/src/utils/utils";
import subjectCompetitionApi from 'common/src/api/subjectCompetition/subjectCompetition';
import mixin from 'common/src/mixins/index';
import viewAdmissionCard from '../mandarin/examsCreate/viewAdmissionCard';
import { pay } from "common/src/api/payment";
export default {
  components: {
    viewAdmissionCard
  },
  mixins: [mixin],
  data() {
    return {
      indexSee: 1,
      myRaidersId: '',
      rows: null,
      dataFormList: {}, //接收路由跳转的数据
      dataForm: {

      }, //表格数据
      internship: {
        opinion: ''
      },

      dataList: [
      ],
      checked: false,
      queryFormType: {
        calendarId: '',
        competitionId: '',
        cardType: '',
      },
      examCampusLimitList: [
        {
          key: '1',
          label: '四平路校区',
          limitNum: '',
          value: '1'
        },
        {
          key: '3',
          label: '嘉定校区',
          limitNum: '',
          value: '3'
        },
      ],
      studentsRegist: {},
      queryFormTypeList: {},
      dialogVisibleTime: false,
      forbidden: false,
      dataTime: new Date(),
      dialogVisible: false,
      dialogVisible2: false,
      outsideAdvisorId: '',
      curCheckStandard: '',
      curPracticeId: '',
      total_: 0,
      queryForm: {
        pageNum_: 1,
        pageSize_: 20,
        condition: {
          calendarId: "",
          examCategory: "6"
        }
      },
      rules: {
        cardType: [{ required: true, message: this.$t('internship.pleaseSelect'), trigger: 'change' }],
        campus: [{ required: true, message: this.$t('internship.pleaseSelect'), trigger: 'change' }]
      },
      options: {
        TrainingLevel: [],
        degreeType: [],
        formLearning: [],
        faculty: [],
        profession: [],
        trainingCategory: []
      },
      tableData: []
    }
  },
  filters: {
    collegeAcademyList(val, array) {
      let str = "";
      for (let item of array) {
        if (val === item.value) {
          str = item.label;
        }
      }
      return str;
    }
  },
  computed: {
    ...mapState({
      mockUser: state => state.session.mockUser,
      uid: state => state.session.uid
    })
  },
  created() {
    this.getOptions();
    window.addEventListener('pageshow', () => {
      if (this.queryForm.condition.calendarId) {
        this.onSubmit()
      }
    })
  },
  activated(){
    if (this.queryForm.condition.calendarId) {
      this.onSubmit()
    }
  },
  mounted() {
    if (this.queryForm.condition.calendarId) {
      this.onSubmit()
    }
  },
  methods: {
    calendarIdLoadDone() {
      this.onSubmit()
    },
    onSubmit() {
      this.queryForm.pageNum_ = 1
      this.getQueryPractice(this.queryForm)
    },
    reset() {
      this.queryForm.condition.calendarId = this.$refs['semester'].currentTermId
      this.queryForm.pageNum_ = 1
      this.getQueryPractice(this.queryForm)
    },
    changeMajor(val) {
      subjectCompetitionApi.informationEnrolled(this.queryFormType).then(res => {
        if (res.code === 200) {
          this.queryFormTypeList = res.data
        }
      });
    },
    getQueryPractice(data) {
      //console.log(data,'data')
      subjectCompetitionApi.computerEnrollment(data).then(res => {
        this.dataList = res.data.list;
        this.total_ = res.data.total_;
        this.dataTime = new Date();
        let dateYear = this.dataTime.getFullYear();             //获取年 
        let dateMonth = this.dataTime.getMonth() + 1;               //获取月  
        let dateDate = this.dataTime.getDate();                 //获取当日
        // let dateDay = date.getDay();                   //获取当日星期数
        let dateHours = this.dataTime.getHours();               //获取小时
        let dateMinutes = this.dataTime.getMinutes();           //获取分钟
        let dateSeconds = this.dataTime.getSeconds();           //获取秒
        // 2020-7-13 11:30:00
        dateMonth = dateMonth >= 10 ? dateMonth : '0' + dateMonth;
        dateDate = dateDate >= 10 ? dateDate : '0' + dateDate;
        dateHours = dateHours >= 10 ? dateHours : '0' + dateHours;
        dateMinutes = dateMinutes >= 10 ? dateMinutes : '0' + dateMinutes;
        dateSeconds = dateSeconds >= 10 ? dateSeconds : '0' + dateSeconds;
        let timeDate = dateYear + '-' + dateMonth + '-' + dateDate + ' ' + dateHours + ':' + dateMinutes + ':' + dateSeconds;
        if (this.dataList) {
          this.dataList.forEach(el => {
            if (el.signUpEnd < timeDate) {
              el.forbidden = true;
            } else {
              el.forbidden = false;
            }
          });
        }
        // console.log(this.dataList);

      });
    },
    getOptions() {
      // 筛选条件字典查询
      let data = {
        lang: this.$store.getters.language || "cn",
        type: "allChild",
        keys: ["X_YX", 'G_ZJLX', "JDJB",]
      };
      queryDic(data).then(res => {
        UTILS.fillSelect(
          {
            facultys: "X_YX",
            degreeType: "G_ZJLX",
            sex: "G_XBIE"
          },
          res.data,
          this.options
        );
        // 1-中华人民共和国居民身份证 01
        // 2-台湾居民往来大陆通行证   13
        // 4-护照  02
        // 5-香港身份证  11
        // 6-澳门身份证  12
        this.options.degreeType = this.options.degreeType.filter(item => {
          return item.value == '01' || item.value == '02' || item.value == '11' || item.value == '12' || item.value == '13'
        })
      });
    },
    // 轮询直到获取key值的接口返回
    cycleToGetKey() {
      setTimeout(() => {
        let currentIds = [];
        if (this.multipleSelection.length > 0) {
          this.multipleSelection.forEach((element) => {
            currentIds.push(element.id);
          });
        }
        subjectCompetitionApi.poststudentExport({
          "competitionId": this.examId,
          "calendarId": this.queryForm.condition.calendarId,
          "college": this.queryForm.condition.collegeName,
          "studentIdOrName": this.queryForm.condition.studentIdOrName,
          "status": this.queryForm.condition.status,
          "selectRowIds": currentIds
        }).then(res => {
          if (res.success) {
            this.$refs.downloadRef.close();
            this.exportButton = false;
            this.normalDelayRequest(res.key, res.msg);
          } else {
            this.cycleToGetKey();
          }
        });
      }, 3000);
    },
    // 导出异步
    delayRequest(key, name) {
      setTimeout(() => {
        subjectCompetitionApi.downloadGetKey(key, name).then(res => {
          this.exportResult = res.data;
          if (res.code == 200 && res.data.status) {
            this.exportButton = false;
            let path =
              '/api/practiceservice/export/file?path=' +
              res.data.path + '&name=' + name;
            // window.open(path);
            window.location.href = path;
            this.$message.success(this.$t('result.exportSuccessfully'));
            this.$refs.downloadRef.close();
          } else {
            this.delayRequest(key, name);
          }
        });
      }, 3000);
    },
    // Normal导出异步
    normalDelayRequest(key, name) {
      setTimeout(() => {
        subjectCompetitionApi.downloadGetKey(key).then(res => {
          this.exportResult = res.data;
          if (res.code == 200 && res.data.status) {
            this.exportButton = false;
            let path =
              '/api/practiceservice/export/file?path=' +
              res.data.path + '&name=' + name;
            // window.open(path);
            window.location.href = path;
            this.$message.success(this.$t('result.exportSuccessfully'));
            this.$refs.downloadRef.close();
          } else {
            this.delayRequest(key, name);
          }
        });
      }, 3000);
    },
    // 导出
    exportAuditRoster() {
      // 1、第一步：调该接口，获取key值以及msg中的文件名
      // 2、第二步：将key值放入接口传参
      // 3、第三步：传入path值以及name(msg中的文件名)值，下载文件
      this.exportResult = null;
      this.$refs.downloadRef.open();
      this.exportButton = true;
      this.cycleToGetKey();
    },
    // 报名
    myRaiders(val) {
      this.rows = val;
      let dataTime = new Date();
      let dateYear = dataTime.getFullYear();             //获取年 
      let dateMonth = dataTime.getMonth() + 1;               //获取月  
      let dateDate = dataTime.getDate();                 //获取当日
      // let dateDay = date.getDay();                   //获取当日星期数
      let dateHours = dataTime.getHours();               //获取小时
      let dateMinutes = dataTime.getMinutes();           //获取分钟
      let dateSeconds = dataTime.getSeconds();           //获取秒
      // 2020-7-13 11:30:00
      dateMonth = dateMonth >= 10 ? dateMonth : '0' + dateMonth;
      dateDate = dateDate >= 10 ? dateDate : '0' + dateDate;
      dateHours = dateHours >= 10 ? dateHours : '0' + dateHours;
      dateMinutes = dateMinutes >= 10 ? dateMinutes : '0' + dateMinutes;
      dateSeconds = dateSeconds >= 10 ? dateSeconds : '0' + dateSeconds;
      let timeDate = dateYear + '-' + dateMonth + '-' + dateDate + ' ' + dateHours + ':' + dateMinutes + ':' + dateSeconds;
      if (val.signUpStart > timeDate) {
        this.dialogVisibleTime = true
      } else {
        this.remark = val.remark;
        this.myRaidersId = val.id;
        this.dialogVisible = true;
      }
    },
    reliable() {
      this.dialogVisible2 = true;
      this.queryFormType.competitionId = this.rows.competitionId;
      this.queryFormType.studentId = this.global.currentUser.uid;
      this.queryFormType.calendarId = this.rows.calendarId;
      subjectCompetitionApi.informationEnrolled(this.queryFormType).then(res => {
        if (res.code === 200) {
          this.studentsRegist = res.data;
          if (this.studentsRegist.campus) {
            this.queryFormType.campus = this.studentsRegist.campus;
          }
        }
      });
    },
    cancelFun() {
      this.dialogVisible = false;
      this.dialogVisible2 = false;
    },
    // 弹框取消
    cancel() {
      this.$set(this.queryFormType, 'campus', '')
      this.queryFormTypeList = {};
      this.studentsRegist = {};
      this.checked = false;
      this.$refs['queryFormType'].resetFields();
      this.dialogVisible = false;
    },
    //查看准考证
    SeeClick(rows) {
      this.signUpId = rows;
      this.indexSee = 2;
    },
    // 返回列表页
    changeExamCreateIndex() {
      this.indexSee = 1
    },
    // 确定报名
    reliable2() {
      this.$refs['queryFormType'].validate(valid => {
        if (valid) {
          let obj = {
            calendarId: this.queryFormType.calendarId,
            examCategory: 6,
            id: this.id,
            major: this.queryFormTypeList.major,
            idCardType: this.queryFormType.cardType,
            idCardNo: this.queryFormTypeList.idCardNo,
            competitionId: this.queryFormType.competitionId,
            studentId: this.queryFormType.studentId,
            campus: this.queryFormType.campus,
            status: 1
          };
          subjectCompetitionApi.computerPostUpdate(obj).then(res => {
            this.$message({
              type: 'success',
              message: this.$t('studentsRegist.successfully')
            });
            this.queryForm.pageNum_ = 1;
            this.getQueryPractice(this.queryForm);
            this.queryFormType.cardType = ''
            this.queryFormType.calendarId = ''
            this.$set(this.queryFormType, 'campus', '')
            this.queryFormTypeList = {};
            this.studentsRegist = {};
            this.checked = false;
            this.$refs['queryFormType'].resetFields();
            this.dialogVisible = false;
            this.dialogVisible2 = false;
          });
        }
      })

    },
    // 取消报名
    cancelRegistr(val) {
      this.$confirm(this.$t('studentsRegist.registration'), this.$t('studentsRegist.cancelRegistr'), {
        confirmButtonText: this.$t('studentsRegist.confirm'),
        cancelButtonText: this.$t('studentsRegist.cancel'),
        type: 'warning'
      }).then(() => {
        let obj = {
          id: val.id,
          status: 0,
          calendarId: val.calendarId,
          examCategory: 6
        };
        subjectCompetitionApi.computerPostUpdate(obj).then(res => {
          this.queryFormTypeList = {};
          this.studentsRegist = {};
          this.queryForm.pageNum_ = 1;
          this.getQueryPractice(this.queryForm);
          this.$message({
            type: 'success',
            message: this.$t('studentsRegist.successfully')
          });
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: this.$t('studentsRegist.canceled')
        });
      });
    },
    //缴费
    // handlePay
    handleClick(rows) {
      var data = {
        studentId: this.global.currentUser.uid,//当前登录用户id或数据行中的学号
        feeItemCode: "jwc2-01",//费用项代码(对外代码)
        projId: 1,//本研
        // faculty: '',//学院
        // term: '',//学期
        // grade: '',//年级
        // major: '',//专业
        callBackData: {
          id: rows.id//回调数据业务数据id
        }
      };
      //return
      pay(data).then(res => {
        if (res.code == 200) {
          top.location.href = res.data; // 跳转
          //window.open(`${res.data}`);             // 新开窗口
          //暂未实现                                // 弹窗
        }
      }).catch(res => {
        console.log(res);
      });
    },
    handleSizeChange(val) {
      this.queryForm.pageSize_ = val;
      this.queryForm.pageNum_ = 1;
      this.getQueryPractice(this.queryForm);
    },
    handleCurrentChange(val) {
      this.queryForm.pageNum_ = val;
      this.getQueryPractice(this.queryForm);
    },
    goBack() {
      this.$store.commit("delete_tabs", this.$route.path);
      this.$router.go(-1);
    },
    // 获取表格数据
    assignment() {

    },
  },
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.inner-breadcrumb {
    .breadcrumb {
        span {
            font-weight: normal;
            color: #aaa;
        }
        a {
            font-weight: normal;
            color: #aaa;
        }
        a:hover {
            color: #409eff;
        }
        .last {
            font-weight: bold !important;
            cursor: default !important;
        }
        .disable {
            cursor: default !important;
        }
    }
}
.condition-title-p {
    font-weight: 400;
    font-style: normal;
    color: #2b3b4e;
    font-size: 18px;
    margin-bottom: 15px;
}
.base-info-title {
    font-weight: 400;
    font-style: normal;
    font-size: 16px;
    color: #2b3b4e;
}
.table-style-baseinfo {
    background-color: rgba(210, 212, 214, 1);
    box-sizing: border-box;
    border-width: 0.5px;
    border-style: solid;
    border-color: rgba(210, 212, 214, 1);
    border-radius: 0px;
    -moz-box-shadow: none;
    -webkit-box-shadow: none;
    box-shadow: none;
    width: 100%;
    font-weight: 401;
    font-style: normal;
    font-size: 14px;
    color: #8896a7;
    margin-bottom: 20px;
}

.table-style-baseinfo td {
    width: 25%;
    background-color: rgba(255, 255, 255, 1);
    border: none;
    border-radius: 0px;
    -moz-box-shadow: none;
    -webkit-box-shadow: none;
    box-shadow: none;
    font-weight: 401;
    font-style: normal;
    font-size: 14px;
    color: #2b3b4e;
    height: 32px;
    padding: 0 10px;
}

.table-style-baseinfo .text-right-background-color {
    background-color: #fdfeff4d;
    text-align: right;
}

.text-left-background-none {
    text-align: left;
}
</style>
